package com.anji.sp.push.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.report.ReceivedsResult;
import com.anji.sp.model.ResponseModel;
import com.anji.sp.push.model.MessageModel;
import com.anji.sp.push.model.po.PushConfiguresPO;
import com.anji.sp.push.model.vo.RequestSendBean;
import com.anji.sp.push.service.PushHistoryService;
import com.anji.sp.push.service.PushService;
import com.anji.sp.util.APPVersionCheckUtil;
import com.anji.sp.util.StringUtils;
import com.xiaomi.push.sdk.ErrorCode;
import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import com.xiaomi.xmpush.server.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


/**
 * <p>
 * 小米推送
 * </p>
 *
 * @author kean
 * @since 2021-01-20
 */
@Service
@Slf4j
public class XiaomiPushServiceImpl implements PushService {

    @Autowired
    private PushHistoryService pushHistoryService;
    @Autowired
    private JPushServiceImpl jPushService;

    @Override
    public ResponseModel pushBatchMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO, String msgId, String targetType) throws Exception {
        if (StringUtils.isEmpty(pushConfiguresPO.getXmAppSecret())
                || StringUtils.isEmpty(pushConfiguresPO.getPackageName())
                || StringUtils.isEmpty(pushConfiguresPO.getAppKey())) {
            //如果参数不全 那么走极光
            jPushService.pushAndroid(requestSendBean,pushConfiguresPO,msgId,"6",false);
            return ResponseModel.errorMsg("参数配置不全");
        }
        MessageModel messageModel;
        try {
            messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        } catch (Exception e) {
            //发送失败重新尝试一次
            messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        }
        //判断成功数是否是0
        if (APPVersionCheckUtil.strToInt(messageModel.getSuccessNum()) == 0){
            return jPushService.pushAndroid(requestSendBean, pushConfiguresPO, msgId, "6", false);
        }
        return pushHistoryService.savePushHistory(requestSendBean, messageModel, msgId, targetType);
    }

    @Override
    public ResponseModel pushAllMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO, String msgId, String targetType) throws Exception {
        if (StringUtils.isEmpty(pushConfiguresPO.getXmAppSecret())
                || StringUtils.isEmpty(pushConfiguresPO.getPackageName())
                || StringUtils.isEmpty(pushConfiguresPO.getAppKey())) {
            //如果参数不全  那么走极光
            jPushService.pushAndroid(requestSendBean,pushConfiguresPO,msgId,"6",false);
            return ResponseModel.errorMsg("参数配置不全");
        }
        MessageModel messageModel = pushMessage(requestSendBean, pushConfiguresPO);
        return pushHistoryService.savePushHistory(requestSendBean, messageModel, msgId, targetType);
    }

    private MessageModel pushMessage(RequestSendBean requestSendBean, PushConfiguresPO pushConfiguresPO) {
        Constants.useOfficial();
        Sender sender = new Sender(pushConfiguresPO.getXmAppSecret());
        String messagePayload = requestSendBean.getContent();
        Result result = null;
        try {
            if (requestSendBean.getExtras() == null) {
                Message message = new Message.Builder()
                        .title(requestSendBean.getTitle())
                        .extra("callback","http://open-appsp.anji-plus.com/push/pushXiaomiCallBack")
                        .extra("callback.param","小米自定义参数")
                        .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT , Constants.NOTIFY_LAUNCHER_ACTIVITY) // 打开当前app对应的Launcher Activity
                        .description(requestSendBean.getContent()).payload(messagePayload)
                        .restrictedPackageName(pushConfiguresPO.getPackageName())
                        .notifyType(1).build();  // 使用默认提示音提示
                result = sender.send(message, requestSendBean.getTokens(), 3);
            } else {
                Message message = new Message.Builder()
                        .title(requestSendBean.getTitle())
                        .description(requestSendBean.getContent()).payload(messagePayload)
                        .restrictedPackageName(pushConfiguresPO.getPackageName())
                        .extra(requestSendBean.getExtras())
                        .extra("callback","http://open-appsp.anji-plus.com/push/pushXiaomiCallBack")
                        .extra("callback.param","小米自定义参数")
                        .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY) // 打开当前app对应的Launcher Activity
                        .notifyType(1).build();  // 使用默认提示音提示
                result = sender.send(message, requestSendBean.getTokens(), 3);
            }
            jPushService.setPassThrougnMsg(requestSendBean, pushConfiguresPO);
            //根据msgId再查询信息 看下有没有方法 没有就根据状态直接返回成功失败
            log.info("XiaomiPush.pushMessage result {}", result);
            if (result.getErrorCode().equals(ErrorCode.Success)) {
                return MessageModel.success(requestSendBean.getTokens().size(), requestSendBean.getTokens().size(),"发送成功\n");
            }else {
                return MessageModel.errorMsg(requestSendBean.getTokens().size(), 0, result.getErrorCode().getDescription()+"\n");
            }
        } catch (IOException e) {
            log.error("XiaomiPush.pushMessage IOException .", e);
            return MessageModel.errorMsg(requestSendBean.getTokens().size(), 0, e.getMessage()+"\n");
        } catch (Exception e) {
            log.error("XiaomiPush.pushMessage Exception .", e);
            return MessageModel.errorMsg(requestSendBean.getTokens().size(), 0, e.getMessage()+"\n");

        }

    }


    /**
     * 查询结果
     * @param xiaomiMsgId
     * @param xmAppSecret
     * @return
     */
    public ResponseModel getXiaoMiMessageStatus(String xiaomiMsgId, String xmAppSecret) {
        Tracer tracer = new Tracer(xmAppSecret); // 使用AppSecretKey创建一个Tracer对象
        // 获取单条消息的送达状态， 参数:msgId, retry次数
        String messageStatus = null;
        try {
            messageStatus = tracer.getMessageStatus(xiaomiMsgId, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseModel.successData(messageStatus);
    }


}
